import os.path
from config import config
import misc
import sd

maxHostID = 1000

class SafeLease:
    params = {sd.LOCK_POLICY : "ON",
              sd.LEASE_RETRIES : 3,
              sd.LEASE_TIME_SEC : 30,
              sd.LOCK_RENEWAL_INTERVAL_SEC : 5,
              sd.IO_OP_TIMEOUT_SEC : 1}

    def __init__(self, lockRenewalIntervalSec, leaseTimeSec, ioOpTimeoutSec, leaseRetries):
        if lockRenewalIntervalSec and leaseTimeSec and ioOpTimeoutSec and leaseRetries:
            self.params = {sd.LEASE_RETRIES : leaseRetries,
                           sd.LEASE_TIME_SEC : leaseTimeSec,
                           sd.LOCK_RENEWAL_INTERVAL_SEC : lockRenewalIntervalSec,
                           sd.IO_OP_TIMEOUT_SEC : ioOpTimeoutSec}

    def __str__(self):
        s = ""
        for name in self.params:
            s += "%s=%s " % (name, self.params[name])
        return s

    def __getitem__(self, val):
        return self.params.get(val, None)

    def getAllParams(self):
        return self.params.copy()

def initLock(path):
# Initialize an empty lease
    lockUtilPath = config.get('irs', 'lock_util_path')
    lockCmd = os.path.join(lockUtilPath, "safelease")
    initCommand = [ str(lockCmd), "release", "-f", str(path), "0" ]
    return misc.execCmd(initCommand, sudo=False, cwd=lockUtilPath)

def acquireLock(path, id, leaseTimeSec, ioOpTimeoutSec):
    lockUtilPath = config.get('irs', 'lock_util_path')
    leaseTimeMs = leaseTimeSec * 1000
    ioOpTimeoutMs = ioOpTimeoutSec * 1000
    lockCmd = os.path.join(lockUtilPath, "safelease")
    acquireCommand = [ str(lockCmd), "acquire", str(path), str(id), str(leaseTimeMs), str(ioOpTimeoutMs)]
    return misc.execCmd(acquireCommand, sudo=False, cwd=lockUtilPath)

